#!/usr/bin/python3

"""
1. 校验用户名和密码
2. 设置session数据
3. 设置cookie数据
4. 设置重定向指令 (重定向到信息查看页面 /var/www/cgi/monitor9)
"""

import os
import sys
import string
import random
from datetime import datetime, timedelta
from urllib.parse import parse_qs

import pytz

from lib import (build_session_data, session_dir, session_expire,
                 redirect_url, sid_length, write_session_data)


def get_username_password():
    post_data = sys.stdin.read()
    data = parse_qs(post_data)
    try:
        username = data['username']
        password = data['password']
    except KeyError:
        return None, None
    else:
        return username[0], password[0]


def auth(username, password):
    # 校验用户名和密码是否正确
    for user in users:
        if username == user['username'] and password == user['password']:
            # 登录成功
            return True
    # 登录失败
    return False


def set_session(sid, username):
    # 设置session数据

    # 用构建session数据
    session_data_json = build_session_data(username, session_expire)

    # 写session数据
    write_session_data(sid, session_data_json)


def calc_expire(tz='Asia/Chongqing', **kargs):
    now = datetime.now()
    tz = pytz.timezone(tz)          # 创建时区
    now = tz.localize(now)          # 给时间加上时区信息
    delta = timedelta(**kargs)
    now = now + delta
    return now.strftime('%a, %d %b %Y %H:%M:%S %z')


def set_cookie(sid):
    expires = calc_expire(seconds=session_expire)
    print('Set-Cookie: sessionid=%s; expires=%s' % (sid, expires))


def set_redirect():
    print('Status: 302')
    print('Location: %s' % redirect_url)


def gen_sid():
    chars = string.ascii_letters + string.digits
    picked = [random.choice(chars) for x in range(sid_length)]
    return ''.join(picked)


users = [
    {'username': 'alice', 'password': 'abc'},
    {'username': 'bob', 'password': 'abc'},
    {'username': 'charlie', 'password': 'abc'},
]


if __name__ == '__main__':
    print('Content-Type: text/html')

    # 获取用户名和密码
    username, password = get_username_password()

    if username and password and auth(username, password):
        # 成功，设置session数据，设置cookie，设置重定向指令
        sid = gen_sid()
        set_session(sid, username)
        set_cookie(sid)
        set_redirect()
        print()
    else:
        # 失败，给出提示信息，让用户重试
        html = "login failed, click <a href='/login9.html'>here</a> to retry"
        print()     # 空行
        print(html)
